import org.codehaus.groovy.grails.commons.ConfigurationHolder
import de.motsangria.exceptions.JabberIdNotFoundException
import de.motsangria.exceptions.JabberIdNotFoundException

class JabberService {

  boolean transactional = false

  static expose = ['jabber']


  def onJabberMessage = {msg ->
    log.info "Eeek a message!!! From ${msg.from} with body ${msg.body}"

    if (msg.body != null && msg.body != '') {
      //Determine Jabber ID and find corresponding user
      def jabberId = ""
      def jabberService = ""
      try {
        def jabberDetails = msg.from.tokenize('/')
        jabberId = jabberDetails[0]
        jabberService = jabberDetails[1]
        if (jabberService.toLowerCase().contains("gmail")) {
          jabberService = "Google Talk"
        } else if (jabberService.toLowerCase().contains("idea")) {
          jabberService = "IdeaTalk"
        } else if (jabberService.toLowerCase().contains("home")) {
          jabberService = "Pidgin"
        }

        def profile = Profile.findByJabberId(jabberId)
        if (!profile) throw new JabberIdNotFoundException("No user with jabber Id '${jabberId}' found.")
        String content = msg.body.encodeAsHTML()
        if (content.length() > 255) {
          content = content[0..249] + ' [...]'
        }
        def message = new Message(user: profile.user, content: content, medium: "${jabberService}")

        if (!message.hasErrors() && message.save()) {
          sendJabberMessage("$jabberId", "Thx! Message published at the MoTSangria homepage.")
        } else {
          throw new Exception ("Error saving message: ${message.errors}")
        }
      } catch (JabberIdNotFoundException e) {
        log.warn("Received jabber message from ${jabberId} but didn't find corresponding user (message: ${msg.body})")
        sendJabberMessage("$jabberId", "Sorry, I didn't find a user in my database who belongs to jabber id '${jabberId}'.\n Please check your MoTSangria user profile to see if your jabber id is registered correctly.")
      } catch (Exception e) {
        log.error("Error publishing message from jabber service: ${e.message}",e)
        sendJabberMessage("$jabberId", "Sorry, an error occurred while publishing your message:\n ${e.getMessage()} \n Please try again later...")
      }
    }
  }
}
